<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of tfForm
 *
 * @author wlf
 */

if(!defined('TinyFW')) exit('Access denied!');

class tfForm {
    
    private $_action = null;
    private $_method = null;
    private $_name = null;
    private $_id = null;
    private $_title = null;

    private $_summary = null;
    private $_elements = array();
    
    private $_extra = array();
    private $_required = array();


    public function __construct($title, $name, $action, $id='', $method = 'post') {
        $this->_title = $title;
        $this->_name = $name;
        $this->_action = $action;
        $this->_method = $method;
        if($id != '') {
            $this->_id = $id;
        }

        //echo __FILE__ . DS . "tfForm" . DS . $classname . ".php";
        spl_autoload_register(array("tfForm","autoload"));

    }

    public static function autoload($classname){
        if(file_exists(dirname(__FILE__) . DS . "tfForm" . DS . $classname . ".php")) {
            include_once(dirname(__FILE__) . DS . "tfForm" . DS . $classname . ".php");
        }
    }

    public function addElement($element, $is_required = false){

        $this->_elements [] = $element;

        if($is_required) {
            $this->_required[] = $element;
        }
    }

    public function getAction(){
        return $this->_action;
    }

    public function getMethod(){
        return $this->_method;
    }

    public function getName(){
        return $this->_name;
    }

    public function getId(){
        return $this->_id;
    }

    public function getTitle(){
        return $this->_title;
    }
    
    public function getExtra(){
        return $this->_extra;
    }

    public function setExtra($extra) {
        $this->_extra = $extra;
    }

    public function render() {

        $ret = $this->getTitle();
        $ret .= "\r\n<form name='" . $this->getName() . "' id='" . $this->getId() . "' action='" . $this->getAction() . "' method='" . $this->getMethod() . "' " . $this->getExtra() . ">\r\n";
        foreach($this->_elements as $element) {
            if($element->isHidden()) {
                $ret .= $element->render();
            } elseif(! $element->isContainer()) {
                $ret .= "<label for='" . $element->getId() . "'>" . $element->getCaption() . "</label><br />" . $element->render() . "<br />\r\n";
            } else {
                //如果是container,直接显示结果，不需要caption
                $ret .= $element->render()."<br/>\r\n";
                
            }
        }
        $ret .= "</form>\r\n";

        return $ret;
    }

    

    public function renderValidationJS() {
        //implement later
    }
    
    public function  __toString() {
        return $this->render();
    }

}

?>
